$('.index').click(function() {
	$('.center').html('');
	$('.nav li').removeClass('active')
	$('.center').load('./' + $(this).attr('index') + '.html');
})

var sno = $.session.get("sno");

if($.session.get("sno_flag") == 0) {
	sno = $.session.get("sno");
} else {
	$('#btn_photo').css("display", "none");
	$('#btn_shanchu').css("display", "none");
	sno = $.session.get("sno2");
}

$('#btn_photo').click(function() {
	$('#pootoModal').modal({
		keyboard: true,
		show: true
	})
})

$('#photo_up').click(function() {

	if($('#files').val() == null || $('#files').val() == "") {
		alert("还未选择照片！");
		return;
	}

	if(!fileCountCheck(document.getElementById("files"), 5)) {
		alert('照片的数量不能大于5，请重新选择！');
		return;
	}

	var formData = new FormData($("#form_photo")[0]);

	$.ajax({
		xhrFields: {
			withCredentials: true
		},
		url: getFullURL("user/up-photo"), //请求的url地址
		dataType: "json", //返回格式为json
		async: true, //请求是否异步，默认为异步，这也是ajax重要特性
		data: formData, //参数值
		type: "POST", //请求方式
		cache: false,
		processData: false, // 不加会报错
		contentType: false, // 不加会报错
		success: function(data) {
			if(data.status == 0) {
				alert("照片上传成功！", function() {
					$('.center').html('');
					$('.center').load('./cstudent.html');
				})
			} else {
				alert('照片的数量不能大于5，请重新选择！');
			}
		},
		error: function(err) {
			alert("请求异常，请重新登录！", function() {
				$(location).attr('href', './login.html');
			})
		}
	})
})

$(function() {
	var urlPath = getSourceURL() + sno + ".jpg";

	isRunUrl(urlPath).then(function(data) {
		$('#img_src_3').attr("src", urlPath);
		console.clear();
	}, function(data) {
		console.clear();
		$('#img_src_3').attr("src", "./img/student.jpg");
	})
})

$.ajax({
	url: getFullURL("userInfo"), //请求的url地址
	dataType: "json", //返回格式为json
	async: true, //请求是否异步，默认为异步，这也是ajax重要特性
	data: {
		sno: sno
	}, //参数值
	type: "post", //请求方式
	beforeSend: function(data) {
		//请求前的处理
	},
	success: function(data) {
		// console.log(data.user)
		$('.cstudent').html('')
		$('.cstudent').html(`<h3>` + nullStr(data.user.name) + `</h3>
            <h5>性&emsp;&emsp;别：<span>` + nullStr(data.user.sex) + `</span></h5>
            <h5>专业方向：<span>` + nullStr(data.user.profession) + `</span><span class="index" index='student'><a>个人资料></a></h5>`)

		$('.index').click(function() {
			$('.center').html('');
			$('.nav li').removeClass('active')
			$('.center').load('./' + $(this).attr('index') + '.html');
		})
		//请求成功时处理
	},
	complete: function(data) {
		//请求完成的处理
	},
	error: function(err) {
		alert("请求异常，请重新登录！", function() {
			$(location).attr('href', './login.html');
		})
	}
});

function del() {
	$.ajax({
		xhrFields: {
			withCredentials: true
		},
		url: getFullURL("user/del-photo"), //请求的url地址
		dataType: "json", //返回格式为json
		async: true, //请求是否异步，默认为异步，这也是ajax重要特性
		cache: false,
		data: {
			fileName: $.session.get("del_id")
		}, //参数值
		type: "POST", //请求方式
		success: function(data) {
			if(data.status == 0) {
				alert("删除照片成功！(如出现照片删除失败请刷新)", function() {
					$.session.set("home_path", 'cstudent');
					window.location.href = "./home.html";
				})
			}
		},
		error: function(err) {
			alert("请求异常，请重新登录！", function() {
				$(location).attr('href', './login.html');
			})
		}
	})
}

var myajax = $.ajax({
	xhrFields: {
		withCredentials: true
	},
	url: getFullURL("get-photo"), //请求的url地址
	dataType: "json", //返回格式为json
	async: true, //请求是否异步，默认为异步，这也是ajax重要特性
	cache: false,
	data: {
		sno: sno
	}, //参数值
	type: "GET", //请求方式
	success: function(data) {
		console.log(data.list);

		var list = data.list;

		if(list == null) {
			$('#next').css('display', 'none');
			$('#prev').css('display', 'none');
			$('#btn_shanchu').css('display', 'none');
			return;
		} else {
			if(list.length == 0) {
				$('#next').css('display', 'none');
				$('#prev').css('display', 'none');
				$('#btn_shanchu').css('display', 'none');
				return;
			}
		}

		$('#imgss').html('');

		////////////////////
		var str_id_ = list[0];
		str_id_ = str_id_.split("\.");
		str_id_ = str_id_[0];
		var str = ``;
		str = `
			<div class="item active" id="item" value="` + list[0] + `">
			    <input type="hidden" class="hideen_img" value="` + list[0] + `"/>
				<img class="imgsss" style="height: 500px;" src="` + getSourceURLPhoto() + sno + "/" + list[0] + `" alt="照片墙">
			</div>
		`;
		$('#imgss').append(str);
		///////////////////
		for(var i = 1; i < list.length; i++) {
			str = ``;
			var str_id = list[i];
			str_id = str_id.split("\.");
			str_id = str_id[0];
			str = `
				<div class="item" id="item" value="` + list[i] + `">
					<input type="hidden" class="hideen_img" value="` + list[i] + `"/>
					<img class="imgsss" style="height: 500px;" src="` + getSourceURLPhoto() + sno + "/" + list[i] + `" alt="照片墙">
				</div>
			`;
			$('#imgss').append(str);
		}
	},
	error: function(err) {
		alert("请求异常，请重新登录！", function() {
			$(location).attr('href', './login.html');
		})
	}
});

$.when(myajax).done(function() {
	// setTimeout(console.log($('.item img').css('height')),2000)
	var div = document.getElementsByClassName('barrage-container-wrap')[0]
	changeMargin();
	window.onresize = function() {
		changeMargin();
	};

	function changeMargin() {
		// console.log($(window).width())
		var docWidth = document.body.clientWidth;
		if(docWidth <= 1200) {
			div.style.height = '300px'
			//   div.style.display='none'
		} else {
			div.style.height = '420px'
		}

	}
	///////////////////////////////

	$("#btn_shanchu").click(function() {

		var value;

		$(".item").each(function(index, element) {
			if($(this).hasClass("active")) {
				value = $(this).attr("value");
			}
		});

		console.log(value);
		$.session.set('del_id', value);
		del();
	})

	$.ajax({
		xhrFields: {
			withCredentials: true
		},
		url: getFullURL("get-barrage"), //请求的url地址
		dataType: "json", //返回格式为json
		async: true, //请求是否异步，默认为异步，这也是ajax重要特性
		data: {
			sno: sno
		}, //参数值
		type: "get", //请求方式
		success: function(data) {
			console.log(data.list)
			barrageArray = data.list
			danmu()
			ss()
		},
		error: function(err) {
			alert("请求异常，请重新登录！", function() {
				$(location).attr('href', './login.html');
			})
		}
	});

	function danmu() {
		var barrageColorArray = [
			'#0099CC', '#333333', '#009966', '#9933FF', '#CC9933', '#000000'
		];
		var barrageTipWidth = 50; //提示语的长度

		var barrageBoxWrap = document.querySelector('.barrage-container-wrap');;
		var barrageBox = document.querySelector('.barrage-container');
		var inputBox = document.querySelector('.input');
		var sendBtn = document.querySelector('.send-btn');

		//容器的宽高度
		var barrageWidth = ~~window.getComputedStyle(barrageBoxWrap).width.replace('px', '');
		var barrageHeight = ~~window.getComputedStyle(barrageBoxWrap).height.replace('px', '');

		//		//发送
		//		function sendMsg() {
		//			var inputValue = inputBox.value;
		//			inputValue.replace(/\ +/g, "");
		//
		//			if(inputValue.length <= 0) {
		//				alert('请输入');
		//				return false;
		//			}
		//          生成弹幕
		//			createBarrage(inputValue, true);
		//			inputBox.value = '';
		//		}

		//创建弹幕
		function createBarrage(msg, isSendMsg) {
			var divNode = document.createElement('div');
			var spanNode = document.createElement('span');

			divNode.innerHTML = msg;
			divNode.classList.add('barrage-item');
			barrageBox.appendChild(divNode);

			spanNode.innerHTML = '举报';

			spanNode.classList.add('barrage-tip');
			divNode.appendChild(spanNode);

			barrageOffsetLeft = getRandom(barrageWidth, barrageWidth * 2);
			barrageOffsetLeft = isSendMsg ? barrageWidth : barrageOffsetLeft
			barrageOffsetTop = getRandom(10, barrageHeight);
			barrageColor = barrageColorArray[Math.floor(Math.random() * (barrageColorArray.length))];

			//执行初始化滚动
			initBarrage.call(divNode, {
				left: barrageOffsetLeft,
				top: barrageOffsetTop,
				color: barrageColor
			});
		}

		//初始化弹幕移动(速度，延迟)
		function initBarrage(obj) {
			//初始化
			obj.top = obj.top || 0;
			obj.class = obj.color || '#fff';
			this.style.left = obj.left + 'px';
			this.style.top = obj.top + 'px';
			this.style.color = obj.color;

			//添加属性
			this.distance = 0;
			this.width = ~~window.getComputedStyle(this).width.replace('px', '');
			this.offsetLeft = obj.left;
			this.timer = null;

			//弹幕子节点
			//var barrageChileNode = this.children[0];
			//barrageChileNode.style.left = (this.width-barrageTipWidth)/2 + 'px';

			//运动
			barrageAnimate(this);

			//停止
			this.onmouseenter = function() {
				//barrageChileNode.style.display = 'block';
				cancelAnimationFrame(this.timer);
			};

			this.onmouseleave = function() {
				//barrageChileNode.style.display = 'none';
				barrageAnimate(this);
			};

			// 举报
			//			barrageChileNode.onclick = function() {
			//				alert('举报成功');
			//			}
		}

		//弹幕动画
		function barrageAnimate(obj) {
			move(obj);

			if(Math.abs(obj.distance) < obj.width + obj.offsetLeft) {
				obj.timer = requestAnimationFrame(function() {
					barrageAnimate(obj);
				});
			} else {
				cancelAnimationFrame(obj.timer);
				//删除节点
				obj.parentNode.removeChild(obj);
			}
		}

		//移动
		function move(obj) {
			obj.distance--;
			obj.style.transform = 'translateX(' + obj.distance + 'px)';
			obj.style.webkitTransform = 'translateX(' + obj.distance + 'px)';
		}

		//随机获取高度
		function getRandom(start, end) {
			return start + parseInt((Math.random() * (end - start - 10)));
		}

		/*******初始化事件**********/
		//系统数据
		barrageArray.forEach(function(item, index) {
			createBarrage(item, false);
		});

		//点击发送
		//sendBtn.onclick = sendMsg; //点击发送

		//回车
		//		inputBox.onkeydown = function(e) {
		//			e = e || window.event;
		//			//   console.log(e)
		//			if(e.keyCode == 13) {
		//				sendMsg()
		//			}
		//		}

	}
	//danmu()

	//兼容写法
	function ss() {
		var lastTime = 0;
		var vendors = ['webkit', 'moz'];
		for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
			window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
			window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || // Webkit中此取消方法的名字变了
				window[vendors[x] + 'CancelRequestAnimationFrame'];
		}

		if(!window.requestAnimationFrame) {
			window.requestAnimationFrame = function(callback, element) {
				var currTime = new Date().getTime();
				var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
				var id = window.setTimeout(function() {
					callback(currTime + timeToCall);
				}, timeToCall);
				lastTime = currTime + timeToCall;
				return id;
			};
		}
		if(!window.cancelAnimationFrame) {
			window.cancelAnimationFrame = function(id) {
				clearTimeout(id);
			};
		}
	}
	//ss()

	$('#btn_danmu').click(function() {
		if($('#danmu').val() == "" || $('#danmu').val() == null) {
			alert("你还未编辑弹幕内容！");
			return;
		}

		$.ajax({
			xhrFields: {
				withCredentials: true
			},
			url: getFullURL("send-barrage"), //请求的url地址
			dataType: "json", //返回格式为json
			async: true, //请求是否异步，默认为异步，这也是ajax重要特性
			data: {
				sno: sno,
				context: $('#danmu').val()
			}, //参数值
			type: "post", //请求方式
			success: function(data) {
				if(data.status == 0) {
					danmu()
					ss()
					alert("发送成功！");
				}
			},
			error: function(err) {
				alert("请求异常，请重新登录！", function() {
					$(location).attr('href', './login.html');
				})
			}
		})
	})

});

function getFilesVal(id) {
	var t_files = $(id).prop('files');
	var str = '';
	for(var i = 0, len = t_files.length; i < len; i++) {
		console.log(t_files[i]);
		str += t_files[i].name + ';';
	};
	return str;
}